package com.richman.ps38;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import com.richman.controller.DecreseRatio;
import com.richman.utils.Common;



public class PS38Selenium {

	
	
	CloseableHttpClient httpClient = null;
	RequestConfig requestConfig = null;
	HttpClientContext clientContext = null;
	
	private static final Random random = new Random();
	
	WebDriver driver = null;
	public String period = "";
	public Vector<String[]> ratios = new Vector<String[]>();
	
	int defaultTimeout = 15*1000;
	long refreshTime = 0;
	
	 {
		 
		
		 
	    requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
	    requestConfig = RequestConfig.copy(requestConfig).setRedirectsEnabled(false).build();//禁止重定向 ， 以便获取cookieb18
	    requestConfig = RequestConfig.copy(requestConfig).setConnectTimeout(defaultTimeout).setConnectionRequestTimeout(defaultTimeout).setSocketTimeout(defaultTimeout).build();//设置超时
	    httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
	 }
	
	
	String withoutMemberServiceCookie = "";
	
	String withMenberService = "";
	
	Map<String, String> myCookies = new HashMap<String, String>();
	
	String ADDRESS = "https://www.ps3838.com/";
	
	String ACCOUNT = "004Z000006";
	String PWD = "aaaa2345";
	String SEARCHCODE = "";
	String BASICRATIO = "";
	
	int grabEventsfailtimes = 0;
	
	long loginTime = 0L;
	
    //-1 最初状态  ,  1登录成功  2抓取成功
    int statusCode = -1;
	
    public  void setLoginParams(String address, String account, String pwd, String searchCode, String basic){
		
			ADDRESS = address;
			ACCOUNT = account;
			PWD = pwd;
			SEARCHCODE = searchCode;
			BASICRATIO= basic;
	}
    
    public int getStatusCode() {

   	 return statusCode;
    }
    
    
    public void updateStatusCode(int i) {

   	 if(i!= 3) {
   		System.out.println(ACCOUNT + ": update ps38_statusCode from " +   Integer.toString(statusCode) + " to " + Integer.toString(i));
   	 }
   	 
   	 if(i == -3) {
   		grabEventsfailtimes++;
   	 }
   	 
   	 if(i ==3) {
   		grabEventsfailtimes = 0;
   	 }
   	 
   	 if(grabEventsfailtimes > 10) {
   		 
   		grabEventsfailtimes = 0;
   		 
   		 System.out.println("grab failed times big than 10 need relogin");
   		 
   		 i = -1;
   	 }
   	 
   	 statusCode = i;
    }
    
    
    public String getAccount() {
    	return ACCOUNT;
    }
    
    
	
    
    
    
    
    
    public String getMatches() {
        try {
        	ratios.clear();
        	//Random random = new Random();            
            // 生成一个介于 10 和 15 之间的随机数（包括 10，但不包括 15）
            //int randomNumber = random.nextInt(6) + 10;
        	
        	if(System.currentTimeMillis()-refreshTime>12*60*1000) {
        		Common.logOut(ACCOUNT+ "  refresh");
        		driver.navigate().refresh();
        		Thread.sleep(6000);
        		
        		String res = driver.getPageSource();
                if(res.contains("特码")) {
                    WebElement leftMenuDiv = driver.findElement(By.className("left-menu"));
                    WebElement vanRowDiv = leftMenuDiv.findElement(By.className("van-row"));
                    WebElement specialDiv = vanRowDiv.findElement(By.xpath(".//div[text()='特码']"));
                    
                    JavascriptExecutor executor = (JavascriptExecutor) driver;
                    executor.executeScript("arguments[0].click();", specialDiv);
                    Thread.sleep(3000);     
                }
        		
        		refreshTime = System.currentTimeMillis();
        	}
        	Common.logOut("Grab " + ACCOUNT);
            String res = driver.getPageSource();
            if(res.contains("special-content")) {
                WebElement rightContentDiv = driver.findElement(By.className("right-content"));
                WebElement SepcialContentDiv = rightContentDiv.findElement(By.className("special-content"));
                                
                List<WebElement> numbers = SepcialContentDiv.findElements(By.cssSelector(".special-content_odds-div span"));
                List<WebElement> values = SepcialContentDiv.findElements(By.cssSelector(".special-content_odds-div i"));

                for (int i = 0; i < numbers.size(); i++) {
                    WebElement number = numbers.get(i);
                    WebElement value = values.get(i);

                    String numberText = number.getAttribute("innerHTML");
                    String valueText = value.getAttribute("innerHTML");
                    System.out.println("numberText:"+numberText + " value:" + valueText);
                    String[] item = {numberText,valueText};
                    ratios.add(item);
                }
                                
                WebElement countdownDiv = driver.findElement(By.className("countdown"));
                List<WebElement> spans = countdownDiv.findElements(By.cssSelector(".countdown span"));
                period = spans.get(0).getAttribute("innerHTML");
                
                //找上一期开奖结果
                WebElement openDiv = driver.findElement(By.className("open"));
                WebElement leftDiv = openDiv.findElement(By.className("left"));
                List<WebElement> spans1 = leftDiv.findElements(By.cssSelector(".left span"));
                String previousPeriod = spans1.get(0).getAttribute("innerHTML");
                
                String result = "";
                WebElement rightDiv = openDiv.findElement(By.className("right"));
                List<WebElement> is = rightDiv.findElements(By.cssSelector(".right i"));
                
                Vector<String> previousPeriodRes = new Vector<String>();
                for (int i = 0; i < is.size(); i++) {
                	WebElement restmp = is.get(i);
                	previousPeriodRes.add(restmp.getAttribute("innerHTML"));
                }
                if(previousPeriodRes.size()==8&&previousPeriodRes.elementAt(6).equals(previousPeriodRes.elementAt(7))) {
                	previousPeriodRes.remove(7);
                }
                
//                for(int i = 0; i < previousPeriodRes.size(); i++) {
//                	System.out.println(previousPeriodRes.elementAt(i));
//                }
                DecreseRatio.ps38GrabThread.ps38Manager.updatePeriodRes(previousPeriod, previousPeriodRes);
                updateStatusCode(3);
                return "";
            }else {
            	Common.logOut(res);
            	//Thread.sleep(3*60*1000);
            }

            

        }catch (Exception e){
        	e.printStackTrace();
        }
        
        driver.quit();
        updateStatusCode(-1);
        
        return null;

    }
    

    
    
    
    

    
    public int Login() {

    	try {
    		driver.quit();
    		Thread.sleep(1000);
    	}catch(Exception e) {
    		
    	}
    	
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setExperimentalOption("detach", true);
        chromeOptions.addArguments("--disable-blink-features=AutomationControlled");
        chromeOptions.setExperimentalOption("useAutomationExtension", false);
        chromeOptions.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
        driver = new ChromeDriver(chromeOptions);
    	
    	try {
    		
    		//WAP 端
            driver.manage().window().maximize();
            driver.get(ADDRESS+"/wap");
            Thread.sleep(7000);
            
            if(driver.getPageSource().contains("请稍后")) {
            	DecreseRatio.ps38GrabThread.canLoginTime = System.currentTimeMillis() + 15*60*1000;
            }
            
            if(driver.getPageSource().contains("van-field-1-input")) {
                driver.findElement(By.id("van-field-1-input")).sendKeys(new  String[] {ACCOUNT});
                Thread.sleep(2000);
                driver.findElement(By.id("van-field-2-input")).sendKeys(new  String[] {PWD});
                Thread.sleep(2000);
                if(driver.getPageSource().contains("van-field-3-input")&&driver.getPageSource().contains("captcha")) {
                	WebElement imgElement = driver.findElement(By.className("captcha"));
                	String srcAttributeValue = imgElement.getAttribute("src");
                	
                	String base64Image = srcAttributeValue.split(",")[1];

                    // Decode the Base64-encoded image data
                    byte[] decodedBytes = Base64.getDecoder().decode(base64Image);

                    // Specify the path to save the image
                    String filePath = ACCOUNT+"image.png";

                    // Save the decoded image data to a file
                    try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
                        outputStream.write(decodedBytes);
                        System.out.println("Image saved successfully at: " + filePath);
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.err.println("Failed to save image.");
                    }

                    File fileBody = new File(filePath);

                    // Build multipart request entity
                    HttpEntity multipartEntity = MultipartEntityBuilder.create()
                            .addBinaryBody("file", fileBody)
                            .addTextBody("fileType", "png")
                            .build();
                    HttpPost httpPost = new HttpPost("http://43.129.194.218:5000/ocr");
                    
                    httpPost.setEntity(multipartEntity);
                    
                    HttpResponse response = httpClient.execute(httpPost);

                    // Get the response body
                    String responseBody = EntityUtils.toString(response.getEntity());
                    
                    String captcha = "";
                    if(responseBody!=null&&responseBody.contains("data")) {
                    	JSONObject jb = new JSONObject(responseBody);
                    	captcha = jb.getString("data");
                    }
                    if(captcha.length()==4) {
                    	driver.findElement(By.id("van-field-3-input")).sendKeys(new  String[] {captcha});
                    }
                    System.out.println(responseBody);
                    
                }
                Thread.sleep(1000);
                driver.findElement(By.cssSelector("button[type='submit']")).click();

                Thread.sleep(5000);
                
                if(driver.getPageSource().contains("立即投注")) {
                	driver.findElement(By.cssSelector("button.van-button.van-button--primary.van-button--normal.btn")).click();
                	Thread.sleep(8000);
                }

                
                String res = driver.getPageSource();
                if(res.contains("特码")) {
                    WebElement leftMenuDiv = driver.findElement(By.className("left-menu"));
                    WebElement vanRowDiv = leftMenuDiv.findElement(By.className("van-row"));
                    WebElement specialDiv = vanRowDiv.findElement(By.xpath(".//div[text()='特码']"));
                    
                    JavascriptExecutor executor = (JavascriptExecutor) driver;
                    executor.executeScript("arguments[0].click();", specialDiv);
                    Thread.sleep(3000);     
                    refreshTime = System.currentTimeMillis();
                	updateStatusCode(1);
                    return 1;
                    
                }else {
                	Common.logOut(ACCOUNT + "no 特码" +res );
                	//Thread.sleep(3*60*1000);
                }
            }
    		
    		//网页端
//            driver.manage().window().maximize();
//            driver.get(ADDRESS+"/#/login?redirect=/home/index");
//            Thread.sleep(5000);
//            
//            if(driver.getPageSource().contains("form_item_account")) {
//                driver.findElement(By.id("form_item_account")).sendKeys(new  String[] {ACCOUNT});
//                driver.findElement(By.id("form_item_password")).sendKeys(new  String[] {PWD});           
//                driver.findElement(By.cssSelector("button.ant-btn.ant-btn-primary.ant-btn-lg.ant-btn-block")).click();
//
//
//
//                Thread.sleep(5000);
//                
//                if(driver.getPageSource().contains("同意")) {
//                	driver.findElement(By.cssSelector("button.ant-btn.ant-btn-primary.btn")).click();
//                	Thread.sleep(8000);
//                }
//
//                if(driver.getPageSource().contains("特码")) {
//                    WebElement leftMenuDiv = driver.findElement(By.className("left-menu"));
//                    WebElement vanRowDiv = leftMenuDiv.findElement(By.className("van-row"));
//                    WebElement specialDiv = vanRowDiv.findElement(By.xpath(".//div[text()='特码']"));
//                    
//                    JavascriptExecutor executor = (JavascriptExecutor) driver;
//                    executor.executeScript("arguments[0].click();", specialDiv);
//                    Thread.sleep(8000);                    
//                	updateStatusCode(1);
//                    return 1;
//                    
//                }
//            }

    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	driver.quit();
    	updateStatusCode(-1);
    	return -1;
    	
    }

}
